# Maroonpu at 2018/1/25
# This script is for MTK SmartConnection(ELIAN)
import os, commands, time, socket

serverIP   = '192.168.123.158'
serverPort = 8988

os.system('iwpriv ra0 elian stop')
os.system('iwpriv ra0 elian start')

while True:
    output = commands.getoutput('iwpriv ra0 elian result')
    if -1 != output.find('rcvFlag'):
        break
    time.sleep(1)

os.system('iwpriv ra0 elian stop')

# Get SSID
startFlag = output.find('ssid=')+5
endFlag   = output.find(', pwd=')	
SSID      = output[startFlag:endFlag]

# Get KEY
startFlag = output.find('pwd=')+4
endFlag   = output.find(', user=')
KEY       = output[startFlag:endFlag]	

# widora connect wifi
os.system('widora_mode client '+SSID+' '+KEY)

time.sleep(10)

# network check
while True:
    pingFlag = os.system('ping -c 1 -q baidu.com')
    if 0 == pingFlag:
        break
    time.sleep(1)

# socket client
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((serverIP, serverPort))
# send flag
s.send('widoraConnect')
while True:
    rcvData = s.recv(15)
    # receive server flag
    if 'serverRcv' == rcvData:
        break
s.close()

print('Wifi is connected successfully!')
